package cn.chinasyq.photoquan.user.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

import cn.chinasyq.photoquan.R;
import cn.chinasyq.photoquan.user.mode.UserMode;
import cn.master.util.utils.ResourcesUtils;
import cn.master.util.utils.ToastUtil;
import cn.master.volley.models.response.handler.ResponseHandler;
import cn.master.volley.models.response.handler.ResponseHandler.FailedStatus;
import cn.master.volley.models.response.handler.ResponseHandler.OnFailedListener;
import cn.master.volley.models.response.handler.ResponseHandler.OnSucceedListener;

/**
 * Created by 一搏 on 2015/11/23.
 */
public class RegisterActivity extends Activity implements View.OnClickListener,OnSucceedListener,OnFailedListener {
    private TextView tv_hint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        tv_hint = (TextView) findViewById(R.id.tv_tips);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_close:
                onBackPressed();
                break;
            case R.id.btn_get_code:
                resend(((EditText)findViewById(R.id.et_phone)).getText().toString());
                break;
            case R.id.btn_finish:
                register(((EditText)findViewById(R.id.et_phone)).getText().toString(),((EditText)findViewById(R.id.et_pass)).getText().toString(),((EditText)findViewById(R.id.et_code)).getText().toString());
                break;
            default:
                break;
        }
    }
    private final String TAG_REGISTER = "register";
    private final String TAG_RECODE = "recode";
    private void resend(String phone) {
        ResponseHandler resetHandler = new ResponseHandler(TAG_RECODE);
        resetHandler.setOnFailedListener(this);
        resetHandler.setOnSucceedListener(this);
        UserMode.sendCaptcha(phone, resetHandler);
    }
    private void register(String phone, String pass, String code) {
        ResponseHandler regHandler = new ResponseHandler(TAG_REGISTER);
        regHandler.setOnFailedListener(this);
        regHandler.setOnSucceedListener(this);
        UserMode.register(phone, pass, code, regHandler);
    }
    private int waitTime=60;
    private boolean isCanSend;
    private final Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    ((TextView)findViewById(R.id.btn_get_code)).setText((String) msg.obj);
                    break;
                case 2:
                    findViewById(R.id.btn_get_code).setEnabled((Boolean) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 调用计时器，倒计时
     */
    private void countDown() {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (--waitTime > 0) {
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = waitTime + getString(R.string.second);
                    handler.sendMessage(msg);
                    isCanSend = false;
                } else {
                    isCanSend = true;
                }
                if (isCanSend) {
                    waitTime = 60;
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = getString(R.string.get_re_verification_code);
                    handler.sendMessage(msg);
                    timer.cancel();
                }
                Message msg = new Message();
                msg.obj = isCanSend;
                msg.what = 2;
                handler.sendMessage(msg);
            }

        }, 0, 1000);
    }
    private void setHint(String str) {
        if (str==null){
            str=(getString(R.string.registration_failed));
        }
        tv_hint.setText(str);
        tv_hint.setVisibility(View.VISIBLE);
    }
    @Override
    public void onFailed(String tag, FailedStatus status, int resultCode,String msg) {
            tv_hint.setVisibility(View.INVISIBLE);
            findViewById(R.id.btn_get_code).setEnabled(true);
        if (msg == null) {
            switch (status) {
                case DATA_ERROR:
                    setHint(ResourcesUtils.getString(getApplicationContext(), resultCode + ""));
                    break;
                case NETWORK_ERROR:
                    setHint(getString(R.string.servererrortips));
                    break;
            }
        }else {
            setHint(msg);
        }
    }

    @Override
    public void onSucceed(String tag, boolean isCache, Object data) {
        tv_hint.setText("");
        if (TAG_RECODE.equals(tag)){
            countDown();
            ToastUtil.show(getApplicationContext(),getString(R.string.verification_code_sent_successfully));
        }else if (TAG_REGISTER.equals(tag)){
            hideSoftKeyboard();
            setResult(RESULT_OK,getIntent());
            finish();
        }
    }
    private void hideSoftKeyboard() {
        if (getCurrentFocus() != null
                && getCurrentFocus().getWindowToken() != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
